<template>
  <div class="create-exam-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-top">
        <el-button class="back-button" @click="handleBack">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <h2>创建考试</h2>
      </div>
      <el-steps :active="activeStep" finish-status="success" simple style="margin: 20px 0">
        <el-step title="基本信息" :status="stepStatus[0]" />
        <el-step title="试题选择" :status="stepStatus[1]" />
        <el-step title="预览发布" :status="stepStatus[2]" />
      </el-steps>
    </div>

    <!-- 步骤内容 -->
    <div class="step-content">
      <!-- 第一步：基本信息 -->
      <div v-if="activeStep === 0" class="basic-info">
        <el-form 
          :model="examForm" 
          :rules="rules" 
          ref="examFormRef" 
          label-width="120px"
          class="exam-form"
        >
          <el-card class="form-card">
            <template #header>
              <div class="card-header">
                <span>考试基本信息</span>
              </div>
            </template>
            
            <el-form-item label="考试名称" prop="name">
              <el-input v-model="examForm.name" placeholder="请输入考试名称" />
        </el-form-item>

            <el-form-item label="考试科目" prop="subject">
              <el-input 
                v-model="examForm.subject" 
                placeholder="请输入考试科目"
              />
        </el-form-item>

            <el-form-item label="考试时长(分钟)" prop="duration">
              <el-input-number 
                v-model="examForm.duration" 
                :min="1" 
                :max="300"
                controls-position="right"
              />
        </el-form-item>

            <el-form-item label="考试时间" required>
              <el-col :span="24">
                <el-form-item prop="startTime">
                  <el-date-picker
                    v-model="examForm.startTime"
                    type="datetime"
                    placeholder="开始时间"
                    style="width: 100%"
                    @change="calculateEndTime"
                  />
        </el-form-item>
              </el-col>
            </el-form-item>

            <el-form-item label="结束时间">
              <el-col :span="24">
                <div class="calculated-time">
                  {{ formatDateTime(examForm.endTime) || '等待设置开始时间和考试时长' }}
      </div>
              </el-col>
          </el-form-item>

            <el-form-item label="总分" prop="totalScore">
              <el-input-number 
                v-model="examForm.totalScore" 
                :min="0" 
                controls-position="right"
              />
          </el-form-item>
          </el-card>
        </el-form>
            </div>

      <!-- 第二步：试题选择 -->
      <div v-if="activeStep === 1" class="question-selection">
        <el-card class="form-card">
          <template #header>
            <div class="card-header">
              <span>组卷方式</span>
            </div>
                </template>
          
          <el-form :model="questionForm" ref="questionFormRef" label-width="120px">
            <el-form-item label="组卷方式" prop="mode" required>
              <el-radio-group v-model="questionForm.mode">
                <el-radio label="random">随机选题</el-radio>
                <el-radio label="manual">手动选题</el-radio>
            </el-radio-group>
          </el-form-item>

            <el-form-item label="选择题库" prop="questionBank" required>
              <el-select v-model="questionForm.questionBank" placeholder="请选择题库" @change="handleQuestionBankChange">
                <el-option 
                  v-for="bank in questionBanks" 
                  :key="bank.questionId" 
                  :label="bank.questionName" 
                  :value="bank.questionName"
                />
              </el-select>
          </el-form-item>
          </el-form>
        </el-card>

        <!-- 随机组题配置 -->
        <el-card v-if="questionForm.mode === 'random'" class="form-card">
          <template #header>
            <div class="card-header">
              <span>随机组题配置</span>
            </div>
                </template>

          <div v-if="questionTypeData.length > 0">
            <div v-for="(typeData, index) in questionTypeData" :key="index" class="question-type-config">
              <h3>{{ typeData.type }}</h3>
              <div class="difficulty-config">
                <div v-for="difficulty in typeData.difficulties" :key="difficulty.level" class="difficulty-item">
                  <span class="difficulty-label">{{ difficulty.level }}：</span>
                  <el-input-number 
                    v-model="randomConfig[typeData.type][difficulty.level].count" 
                    :min="0" 
                    :max="difficulty.count"
                    size="small"
                  />
                  <span class="question-count">/ {{ difficulty.count }}</span>
                  <el-input-number
                    v-model="randomConfig[typeData.type][difficulty.level].score"
                    :min="0"
                    :max="100"
                    size="small"
                    placeholder="分数"
                  />
                  <span>分/题</span>
            </div>
              </div>
            </div>
            <div class="submit-button">
              <el-button type="primary" @click="handleRandomQuestionSubmit">生成试题</el-button>
            </div>
          </div>
          <div v-else class="no-data">
            请先选择题库
          </div>
        </el-card>

        <!-- 手动组题配置 -->
        <el-card v-if="questionForm.mode === 'manual'" class="form-card">
          <template #header>
            <div class="card-header">
              <span>手动选题</span>
            </div>
          </template>

          <div v-if="manualQuestions.length > 0">
            <el-tabs v-model="activeQuestionType">
              <el-tab-pane 
                v-for="type in manualQuestions" 
                :key="type.type" 
                :label="type.type + '(' + type.number + ')'"
                :name="type.type"
              >
                <el-table :data="type.listOfQuestions" style="width: 100%" @selection-change="(selection) => handleQuestionSelect(selection, type.type)">
                  <el-table-column type="selection" width="55" />
                  <el-table-column prop="questionId" label="题号" width="80" />
                  <el-table-column prop="content" label="题目内容" show-overflow-tooltip />
                  <el-table-column prop="difficulty" label="难度" width="100">
                <template #default="scope">
                      <el-tag :type="getDifficultyTag(scope.row.difficulty)">{{ scope.row.difficulty }}</el-tag>
                </template>
              </el-table-column>
                  <el-table-column label="分数" width="150">
                <template #default="scope">
                      <el-input-number
                        v-model="scope.row.score"
                        :min="0"
                        :max="100"
                        :default-value="1"
                        size="small"
                        @change="console.log('分数更新:', scope.row.score)"
                      />
                </template>
              </el-table-column>
                  <el-table-column label="操作" width="120">
                <template #default="scope">
                      <el-button type="primary" link @click="previewQuestion(scope.row)">预览</el-button>
                </template>
              </el-table-column>
            </el-table>
              </el-tab-pane>
            </el-tabs>
            <div class="submit-button">
              <el-button type="primary" @click="handleManualQuestionSubmit">确认选题</el-button>
            </div>
          </div>
          <div v-else class="no-data">
            请先选择题库
          </div>
        </el-card>
      </div>

      <!-- 第三步：预览发布 -->
      <div v-if="activeStep === 2" class="preview-publish">
        <el-card class="preview-card">
          <template #header>
            <div class="card-header">
              <span>考试预览</span>
            </div>
                </template>

          <div class="exam-preview">
            <h3>{{ examForm.name }}</h3>
            <div class="exam-info">
              <p><strong>考试科目：</strong>{{ examForm.subject }}</p>
              <p><strong>考试时长：</strong>{{ examForm.duration }}分钟</p>
              <p><strong>考试时间：</strong>{{ formatDateTime(examForm.startTime) }} - {{ formatDateTime(examForm.endTime) }}</p>
              <p><strong>总分：</strong>{{ examForm.totalScore }}分</p>
              <p><strong>考试说明：</strong></p>
              <div class="exam-description">
                1. 考试时间为{{ examForm.duration }}分钟，请合理分配答题时间。
                2. 考试总分为{{ examForm.totalScore }}分。
                3. 请独立完成考试，不得查阅资料或与他人交流。
                4. 请在规定时间内提交试卷，超时将自动提交。
              </div>
            </div>

            <div class="selected-questions">
              <h4>试题列表</h4>
              <el-table :data="selectedQuestions" style="width: 100%">
                <el-table-column type="index" label="序号" width="80" />
                <el-table-column label="题目类型" width="120">
                <template #default="scope">
                    <el-tag :type="getQuestionTypeTag(scope.row.type)">
                      {{ scope.row.type }}
                    </el-tag>
                </template>
              </el-table-column>
                <el-table-column prop="title" label="题目内容" show-overflow-tooltip />
                <el-table-column prop="score" label="分数" width="80" />
            </el-table>
            </div>

            <div class="total-score">
              实际总分：{{ calculateTotalScore() }}分
      </div>
          </div>
        </el-card>
          </div>
        </div>

    <!-- 底部操作按钮 -->
    <div class="bottom-buttons">
      <el-button v-if="activeStep > 0" @click="prevStep">上一步</el-button>
      <el-button
        v-if="activeStep < 2"
        type="primary"
        @click="nextStep"
      >
        下一步
      </el-button>
      <el-button
        v-else
        type="success"
        @click="handlePublishClick"
      >
        发布考试
      </el-button>
      </div>

    <!-- 试题预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="试题预览"
      width="50%"
    >
      <div class="question-preview" v-if="currentPreviewQuestion">
        <div class="question-type">
          <el-tag :type="getQuestionTypeTag(currentPreviewQuestion.type)">
            {{ currentPreviewQuestion.type }}
          </el-tag>
        </div>
        <div class="question-content">
          <h4>{{ currentPreviewQuestion.title }}</h4>
          <div class="options" v-if="currentPreviewQuestion.type === '单选题' || currentPreviewQuestion.type === '多选题'">
            <div v-for="(option, index) in currentPreviewQuestion.options" :key="index" class="option-item">
              <span class="option-label">{{ String.fromCharCode(65 + index) }}.</span>
              {{ option }}
            </div>
          </div>
          <div class="answer" v-if="currentPreviewQuestion.answer">
            <strong>答案：</strong>{{ currentPreviewQuestion.answer }}
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 发布考试对话框 -->
    <el-dialog
      v-model="publishDialogVisible"
      title="发布考试"
      width="40%"
    >
      <el-form :model="publishForm" label-width="100px">
        <el-form-item label="发布方式">
          <el-radio-group v-model="publishForm.target_type" @change="handleTargetTypeChange">
            <el-radio label="class">按班级发布</el-radio>
            <el-radio label="student">按学生发布</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item :label="publishForm.target_type === 'class' ? '选择班级' : '选择学生'" required>
          <el-select
            v-model="publishForm.target_id"
            multiple
            collapse-tags
            collapse-tags-tooltip
            :placeholder="publishForm.target_type === 'class' ? '请选择班级' : '请选择学生'"
            style="width: 100%"
          >
            <template v-if="publishForm.target_type === 'class'">
              <el-option
                v-for="item in classList"
                :key="item.classId"
                :label="item.className"
                :value="item.classId"
              />
          </template>
            <template v-else>
              <el-option
                v-for="item in studentList"
                :key="item.schoolNumber"
                :label="`${item.name}(${item.className})`"
                :value="item.schoolNumber"
              />
            </template>
          </el-select>
        </el-form-item>
    </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="publishDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="publishExam">确认发布</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { Search, ArrowLeft } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '../../utils/request'
import { useUser } from '../../stores/userInfo'
import { useRouter } from 'vue-router'

const userStore = useUser()
const router = useRouter()

// 当前步骤
const activeStep = ref(0)

// 表单数据
const examForm = reactive({
      name: '',
  subject: '',
  duration: 60,
  startTime: '',
  endTime: '',
  totalScore: 100
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入考试名称', trigger: 'blur' },
    { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
  ],
  subject: [
    { required: true, message: '请输入考试科目', trigger: 'blur' }
  ],
  duration: [
    { required: true, message: '请设置考试时长', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  totalScore: [
    { required: true, message: '请设置总分', trigger: 'blur' }
  ]
}

const examFormRef = ref()

// 试题分类数据
const questionCategories = [
  {
    label: '计算机基础',
    children: [
      { label: '计算机网络' },
      { label: '操作系统' },
      { label: '数据结构' }
    ]
  },
  {
    label: '编程语言',
    children: [
      { label: 'Java' },
      { label: 'Python' },
      { label: 'JavaScript' }
    ]
  }
]

const defaultProps = {
  children: 'children',
  label: 'label'
}

// 试题列表数据
const questions = [
      {
        id: 1,
    type: '单选题',
    title: 'TCP/IP协议中，以下哪个协议工作在传输层？',
    difficulty: 3,
    score: 2,
    options: ['HTTP', 'TCP', 'IP', 'FTP'],
    answer: 'B'
      },
      {
        id: 2,
    type: '多选题',
    title: '以下哪些是JavaScript的数据类型？',
    difficulty: 4,
    score: 4,
    options: ['String', 'Number', 'Boolean', 'Float'],
    answer: 'ABC'
      },
      {
        id: 3,
    type: '判断题',
    title: 'Java中，String类是final的。',
    difficulty: 2,
    score: 2,
    answer: '正确'
  }
]

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const totalQuestions = ref(100)

// 搜索关键词
const searchKeyword = ref('')

// 已选试题
const selectedQuestions = ref([])

// 试题预览相关
const previewDialogVisible = ref(false)
const currentPreviewQuestion = ref(null)

// 计算属性：过滤后的试题列表
const filteredQuestions = computed(() => {
  return questions.filter(question => 
    question.title.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

// 方法
const handleNodeClick = (data) => {
  console.log(data)
}

const handleSelectionChange = (val) => {
  selectedQuestions.value = val
}

const handleSizeChange = (val) => {
  pageSize.value = val
  // 重新加载数据
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  // 重新加载数据
}

const getQuestionTypeTag = (type) => {
  const typeMap = {
    '单选题': '',
    '多选题': 'success',
    '判断题': 'warning',
    '简答题': 'info'
  }
  return typeMap[type] || ''
}

const previewQuestion = (question) => {
  console.log('预览题目:', question)
  // 设置title属性以兼容预览对话框的显示
  currentPreviewQuestion.value = {
    ...question,
    title: question.content || '无内容', // 确保内容显示在标题位置
    type: question.type || '未知类型',   // 确保类型存在
    questionId: question.questionId || 0  // 确保题目ID存在
  }
  previewDialogVisible.value = true
}

const formatDateTime = (dateTime) => {
    if (!dateTime) return '';
    const date = new Date(dateTime);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const calculateEndTime = () => {
    if (examForm.startTime && examForm.duration) {
        const startDate = new Date(examForm.startTime);
        examForm.endTime = new Date(startDate.getTime() + examForm.duration * 60000);
    }
};

const calculateTotalScore = () => {
  return selectedQuestions.value.reduce((total, question) => total + (question.score || 0), 0)
}

const checkTotalScore = () => {
  const currentTotal = calculateTotalScore()
  if (currentTotal !== examForm.totalScore) {
    ElMessage.warning(`当前试题总分(${currentTotal}分)与设定总分(${examForm.totalScore}分)不符，请调整试题分数`)
    return false
  }
  return true
}

const prevStep = () => {
  if (activeStep.value > 0) {
    activeStep.value--
  }
}

const questionForm = reactive({
  mode: 'random',
  questionBank: ''
})

const questionBanks = ref([])
const questionTypeData = ref([])
const manualQuestions = ref([])
const activeQuestionType = ref('')
const randomConfig = ref({})

// 获取题库列表
const getQuestionBanks = async () => {
  try {
    const response = await request({
      url: '/showExam',
      method: 'get',
      params: {
        schoolNumber: userStore.userInfo.schoolNumber
      }
    })
    if (response.code === 200) {
      questionBanks.value = response.data
    }
  } catch (error) {
    console.error('获取题库列表失败：', error)
    ElMessage.error('获取题库列表失败')
  }
}

// 获取题库题型数量信息
const getQuestionTypeInfo = async (questionName) => {
  try {
    const response = await request({
      url: '/getNumberOfDifferentTypes',
      method: 'get',
      params: {
        question_name: questionName
      }
    })
    if (response.code === 200) {
      // 处理数据，将相同题型的不同难度整合在一起
      const processedData = []
      const typeMap = new Map()

      response.data.forEach(item => {
        const type = item.questionTypes[0].type
        const difficulty = item.questionTypes[0].difficulties[0]

        if (!typeMap.has(type)) {
          typeMap.set(type, {
            type,
            difficulties: []
          })
        }
        typeMap.get(type).difficulties.push(difficulty)
      })

      typeMap.forEach(value => {
        processedData.push(value)
      })

      questionTypeData.value = processedData
      // 初始化随机配置
      const config = {}
      processedData.forEach(typeData => {
        config[typeData.type] = {}
        typeData.difficulties.forEach(diff => {
          config[typeData.type][diff.level] = {
            count: 0,
            score: 1
          }
        })
      })
      randomConfig.value = config
    }
  } catch (error) {
    console.error('获取题型信息失败：', error)
    ElMessage.error('获取题型信息失败')
  }
}

// 获取手动组题题目列表
const getManualQuestions = async (questionName) => {
  try {
    const response = await request({
      url: '/getManualQuestion',
      method: 'get',
      params: {
        question_name: questionName
      }
    })
    if (response.code === 200) {
      // 为每个题目设置默认分数1
      manualQuestions.value = response.data.map(type => ({
        ...type,
        listOfQuestions: type.listOfQuestions.map(question => ({
          ...question,
          score: question.score || 0 // 使用已有分数或默认0
        }))
      }))
      if (manualQuestions.value.length > 0) {
        activeQuestionType.value = manualQuestions.value[0].type
      }
    }
  } catch (error) {
    console.error('获取题目列表失败：', error)
    ElMessage.error('获取题目列表失败')
  }
}

// 题库选择变化处理
const handleQuestionBankChange = async (value) => {
  if (questionForm.mode === 'random') {
    await getQuestionTypeInfo(value)
  } else {
    await getManualQuestions(value)
  }
}

// 难度标签样式
const getDifficultyTag = (difficulty) => {
  const difficultyMap = {
    '简单': 'success',
    '中等': 'warning',
    '困难': 'danger'
  }
  return difficultyMap[difficulty] || ''
}

// 选择题目处理
const handleQuestionSelect = (selection, type) => {
  console.log('选择的题目类型:', type)
  console.log('选中的原始试题数据:', selection)
  
  // 获取当前类型的所有题目列表，以便能够获取到最新的分数设置
  const currentTypeQuestionList = manualQuestions.value.find(q => q.type === type)?.listOfQuestions || []
  
  // 创建题目ID到分数的映射，以便快速查找分数
  const scoreMap = {}
  currentTypeQuestionList.forEach(q => {
    if (q.questionId && q.score !== undefined) {
      scoreMap[q.questionId] = q.score
    }
  })
  
  console.log('当前类型题目的分数映射:', scoreMap)
  
  // 确保选中的题目都有正确的type属性和有效的questionId，并且从scoreMap获取最新设置的分数
  const processedSelection = selection.map(item => {
    // 获取用户在界面上设置的最新分数
    const latestScore = item.questionId && scoreMap[item.questionId] !== undefined 
                      ? scoreMap[item.questionId] 
                      : (item.score || 1)
                      
    console.log(`题目${item.questionId}的分数: ${latestScore}`)
    
    return {
      ...item,
      type, // 设置正确的题型
      questionId: item.questionId || 0, // 确保questionId不为undefined
      score: latestScore // 使用用户设置的最新分数
    }
  })
  
  // 获取当前题型的所有已选题目
  const currentTypeQuestions = selectedQuestions.value.filter(q => q.type !== type)
  
  // 合并当前题型新选择的题目和其他题型的已选题目
  selectedQuestions.value = [...currentTypeQuestions, ...processedSelection]
  
  console.log('更新后的已选题目:', selectedQuestions.value)
}

// 添加步骤状态控制
const isQuestionSelected = ref(false)
const stepStatus = computed(() => {
    return {
    0: activeStep.value > 0 ? 'success' : activeStep.value === 0 ? 'process' : 'wait',
    1: isQuestionSelected.value ? 'success' : activeStep.value === 1 ? 'process' : 'wait',
    2: activeStep.value === 2 ? 'process' : 'wait'
  }
})

// 修改下一步方法
const nextStep = async () => {
  if (activeStep.value === 0) {
    console.log('开始验证表单')
    // 第一步验证和处理保持不变
    await examFormRef.value.validate(async (valid) => {
      console.log('表单验证结果:', valid)
      if (valid) {
        try {
          const requestData = {
            examName: examForm.name,
            subject: examForm.subject,
            startTime: formatDateTime(examForm.startTime),
            duration: examForm.duration,
            totalScore: examForm.totalScore,
            teacherId: userStore.userInfo.schoolNumber
          }
          console.log('准备发送的数据:', requestData)

          const response = await request({
            url: '/createExam',
            method: 'post',
            data: requestData
          })

          console.log('创建考试响应：', response)
          if (response.code === 200) {
            console.log('设置考试ID:', response.data)
            examId.value = response.data
            ElMessage.success('考试基本信息保存成功')
            activeStep.value++
            console.log('当前步骤:', activeStep.value)
            // 获取题库列表
            await getQuestionBanks()
          } else {
            console.error('保存失败:', response)
            ElMessage.error(response.message || '保存失败')
          }
        } catch (error) {
          console.error('创建考试失败：', error)
          ElMessage.error('创建考试失败，请重试')
        }
      }
    })
  } else if (activeStep.value === 1) {
    // 检查是否已经组题
    if (!isQuestionSelected.value) {
      ElMessage.warning('请先完成试题组卷')
      return
    }
    // 再次检查总分，以防用户在组题后修改了分数
    if (!checkTotalScore()) {
      return
    }
    activeStep.value = 2
  }
}

// 添加 examId ref
const examId = ref(null)

// 格式化日期为ISO字符串
const formatDateToISO = (date) => {
  if (!date) return ''
  return new Date(date).toISOString().slice(0, 19)
}

// 添加发布方式的响应式数据
const publishForm = reactive({
  target_type: 'class', // 默认按班级发布
  target_id: [], // 发布目标ID列表
})

// 修改发布对话框的显示控制和初始化逻辑
const publishDialogVisible = ref(false)
const classList = ref([])
const studentList = ref([])

// 修改发布对话框打开时的处理
const handlePublishClick = async () => {
  publishForm.target_id = [] // 清空已选择的目标
  publishDialogVisible.value = true
  // 立即获取班级列表
  if (publishForm.target_type === 'class') {
    await getClassList()
  }
}

// 修改发布方式变化的处理方法
const handleTargetTypeChange = async () => {
  publishForm.target_id = [] // 清空已选择的目标
  if (publishForm.target_type === 'class') {
    await getClassList()
  } else if (publishForm.target_type === 'student') {
    await getStudentList()
  }
}

// 修改发布考试方法，重置组题状态
const publishExam = async () => {
  try {
    
    const response = await request({
      url: '/publish',
      method: 'post',
      data: {
        examId: examId.value,
        target_type: publishForm.target_type,
        target_id: publishForm.target_type === 'class' ? publishForm.target_id : publishForm.target_id
      }
    })
    
    if (response.code === 200) {
      ElMessage.success('考试发布成功！')
      publishDialogVisible.value = false
      // 重置表单和状态
      examForm.name = ''
      examForm.subject = ''
      examForm.duration = 60
      examForm.startTime = ''
      examForm.endTime = ''
      examForm.totalScore = 100
      questionForm.mode = 'random'
      questionForm.questionBank = ''
      selectedQuestions.value = []
      isQuestionSelected.value = false  // 重置组题状态
      activeStep.value = 0
      // 可以添加一个确认对话框询问是否继续创建
      ElMessageBox.confirm('是否继续创建新的考试？', '提示', {
        confirmButtonText: '继续创建',
        cancelButtonText: '返回列表',
        type: 'info'
      }).then(() => {
        // 用户选择继续创建，已经重置了表单，停留在当前页面
      }).catch(() => {
        // 用户选择返回列表，跳转到考试管理页面
        router.push('/exam')
      })
    } else {
      // 检查是否有未设置邮箱的学生信息
      if (response.data && response.data.noEmailStudents) {
        const noEmailStudents = response.data.noEmailStudents
        ElMessageBox.alert(
          `以下学生没有邮箱地址，无法发送通知：\n${noEmailStudents.join('、')}`,
          '提示',
          {
            confirmButtonText: '确定',
            type: 'warning'
          }
        )
      } else {
        ElMessage.error(response.message || '发布失败')
      }
    }
  } catch (error) {
    console.error('发布考试失败：', error)
    ElMessage.error('发布考试失败，请重试')
  }
}

// 修改获取班级列表的方法
const getClassList = async () => {
  try {
    const response = await request({
      url: '/getTeacherClasses',
      method: 'get',
      params: {
        teacherId: userStore.userInfo.schoolNumber
      }
    })
    if (response.code === 200) {
      // 直接使用后端返回的数据结构
      classList.value = response.data
      console.log('获取到的班级列表：', classList.value)
    }
  } catch (error) {
    console.error('获取班级列表失败：', error)
    ElMessage.error('获取班级列表失败')
  }
}

// 添加获取学生列表的方法
const getStudentList = async () => {
  try {
    const response = await request({
      url: '/getTeacherStudents',
      method: 'get',
      params: {
        teacherId: userStore.userInfo.schoolNumber
      }
    })
    if (response.code === 200) {
      studentList.value = response.data
    }
  } catch (error) {
    console.error('获取学生列表失败：', error)
    ElMessage.error('获取学生列表失败')
  }
}

// 添加获取预览数据的方法
const getPreviewData = async () => {
  try {
    console.log('获取预览数据，examId:', examId.value)
    const response = await request({
      url: '/getExamPreview',
      method: 'get',
      params: {
        examId: examId.value
      }
    })
    
    console.log('预览数据响应：', response)
    if (response.code === 200) {
      selectedQuestions.value = response.data.map(question => ({
        ...question,
        title: question.content // 确保预览时显示题目内容
      }))
      console.log('处理后的预览数据：', selectedQuestions.value)
      return true
    } else {
      console.error('获取预览数据失败：', response)
      ElMessage.error(response.message || '获取预览数据失败')
      return false
    }
  } catch (error) {
    console.error('获取预览数据失败：', error)
    ElMessage.error('获取预览数据失败')
    return false
  }
}

// 修改随机组题提交方法
const handleRandomQuestionSubmit = async () => {
  if (!questionForm.questionBank) {
    ElMessage.warning('请选择题库')
    return
  }

  const questionTypeConfigs = []
  Object.entries(randomConfig.value).forEach(([type, difficulties]) => {
    const difficultyConfig = {}
    let hasQuestions = false
    let score = 0
    Object.entries(difficulties).forEach(([level, config]) => {
      if (config.count > 0) {
        difficultyConfig[level] = config.count
        hasQuestions = true
        score = config.score
      }
    })
    if (hasQuestions) {
      questionTypeConfigs.push({
        type,
        difficulty: difficultyConfig,
        score
      })
    }
  })

  if (questionTypeConfigs.length === 0) {
    ElMessage.warning('请至少选择一种题型的题目')
    return
  }

  try {
    console.log('发送随机组题请求，参数：', {
      ExamId: examId.value,
      questionName: questionForm.questionBank,
      questionTypeConfigs
    })

    const response = await request({
      url: '/randomQuestion',
      method: 'post',
      params: {
        ExamId: examId.value
      },
      data: {
        questionName: questionForm.questionBank,
        questionTypeConfigs
      }
    })

    console.log('随机组题响应：', response)
    if (response.code === 200) {
      ElMessage.success(response.message || '随机组题成功')
      // 获取预览数据
      const previewSuccess = await getPreviewData()
      if (previewSuccess) {
        // 检查总分
        if (checkTotalScore()) {
          isQuestionSelected.value = true  // 标记组题完成
        } else {
          isQuestionSelected.value = false  // 如果总分不符，不标记完成
        }
      }
    } else {
      console.error('组题失败，响应：', response)
      ElMessage.error(response.message || '随机组题失败')
    }
  } catch (error) {
    console.error('组题失败：', error)
    ElMessage.error('组题失败，请重试')
  }
}

// 修改手动组题提交方法
const handleManualQuestionSubmit = async () => {
  if (selectedQuestions.value.length === 0) {
    ElMessage.warning('请至少选择一道题目')
    return
  }

  // 检查是否有题目缺少questionId或questionId为0
  const invalidQuestions = selectedQuestions.value.filter(q => {
    const questionId = q.questionId
    return !questionId || questionId === 0 || questionId === '0' || isNaN(Number(questionId))
  })

  if (invalidQuestions.length > 0) {
    console.error('存在无效题目ID:', invalidQuestions)
    ElMessage.error('存在无效题目，请重新选择')
    return
  }

  // 为所有已选择的题目创建ID到对象的映射，方便后续更新分数
  const selectedQuestionsMap = {}
  selectedQuestions.value.forEach(q => {
    if (q.questionId) {
      selectedQuestionsMap[q.questionId] = q
    }
  })

  // 更新所有已选题目的分数
  manualQuestions.value.forEach(typeObj => {
    typeObj.listOfQuestions.forEach(q => {
      if (q.questionId && selectedQuestionsMap[q.questionId] && q.score !== undefined) {
        selectedQuestionsMap[q.questionId].score = q.score
      }
    })
  })

  // 创建后端需要的数据结构：每个元素是一个对象，键是题目ID的字符串形式，值是分数
  const questionIds = selectedQuestions.value.map(q => {
    // 确保questionId存在且为有效的数字
    const questionIdStr = String(Number(q.questionId))
    const score = typeof q.score === 'number' ? q.score : 1 // 确保分数是数字，默认为1
    console.log(`提交的题目ID: ${questionIdStr}, 分数: ${score}`)
    return { [questionIdStr]: score }
  })

  console.log('提交的题目数据:', questionIds)

  try {
    const response = await request({
      url: '/manualQuestion',
      method: 'post',
      params: {
        ExamId: examId.value
      },
      data: {
        question_id: questionIds
      }
    })

    if (response.code === 200) {
      await getPreviewData()
      // 检查总分
      if (checkTotalScore()) {
        ElMessage.success('手动组题成功')
        isQuestionSelected.value = true  // 标记组题完成
      } else {
        isQuestionSelected.value = false  // 如果总分不符，不标记完成
      }
    } else {
      ElMessage.error(response.message || '手动组题失败')
    }
  } catch (error) {
    console.error('组题失败：', error)
    ElMessage.error('组题失败，请重试')
  }
}

// 添加样式
const submitButton = {
  marginTop: '20px',
  textAlign: 'center'
}

// 修改预览页面的总分显示样式
const totalScoreClass = computed(() => {
  const currentTotal = calculateTotalScore()
  return {
    'total-score': true,
    'total-score--warning': currentTotal !== examForm.totalScore
  }
})

// 修改返回处理方法
const handleBack = () => {
  ElMessageBox.confirm('确定要返回吗？未保存的内容将会丢失', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    router.push('/main')  // 修改为返回到Main页面
  }).catch(() => {})
}
</script>

<style scoped>
.create-exam-container {
  padding: 30px;
  background-color: #f8fafc;
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 30px;
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.header-top {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
}

.back-button {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 8px 16px;
  font-size: 14px;
  border-radius: 8px;
  background-color: #f8fafc;
  border: 1px solid #e4e7ed;
  color: #606266;
  transition: all 0.3s ease;
}

.back-button:hover {
  background-color: #ecf5ff;
  color: #409EFF;
  border-color: #409EFF;
  transform: translateX(-2px);
}

.page-header h2 {
  margin: 0;
  padding: 0;
  font-size: 28px;
  color: #1a1a1a;
  font-weight: 600;
}

.form-card {
  margin-bottom: 25px;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
  background: white;
  border: none;
  transition: all 0.3s ease;
}

.form-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eef2f7;
}

.card-header span {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  position: relative;
}

.card-header span::after {
  content: '';
  position: absolute;
  bottom: -5px;
  left: 0;
  width: 40px;
  height: 3px;
  background: #409EFF;
  border-radius: 3px;
}

.exam-form {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.exam-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #2c3e50;
}

.exam-form :deep(.el-input__wrapper),
.exam-form :deep(.el-textarea__wrapper) {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  border-radius: 8px;
}

.exam-form :deep(.el-input__wrapper:hover),
.exam-form :deep(.el-textarea__wrapper:hover) {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.bottom-buttons {
  margin-top: 30px;
  display: flex;
  justify-content: center;
  gap: 15px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.bottom-buttons .el-button {
  padding: 12px 30px;
  font-size: 16px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.bottom-buttons .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.preview-card {
  margin: 0 auto;
  max-width: 1000px;
}

.exam-preview {
  padding: 30px;
}

.exam-preview h3 {
  font-size: 24px;
  color: #2c3e50;
  margin-bottom: 25px;
  text-align: center;
  font-weight: 600;
}

.exam-info {
  margin: 25px 0;
  padding: 20px;
  background-color: #f8fafc;
  border-radius: 12px;
  border: 1px solid #eef2f7;
}

.exam-info p {
  margin: 12px 0;
  font-size: 15px;
  color: #2c3e50;
  line-height: 1.6;
}

.exam-info p strong {
  color: #1a1a1a;
  margin-right: 8px;
}

.exam-description {
  background-color: #f8fafc;
  padding: 20px;
  border-radius: 12px;
  margin-top: 15px;
  line-height: 1.8;
  color: #2c3e50;
  border: 1px solid #eef2f7;
}

.selected-questions {
  margin-top: 30px;
}

.selected-questions h4 {
  font-size: 20px;
  color: #2c3e50;
  margin-bottom: 20px;
  font-weight: 600;
}

.total-score {
  margin-top: 25px;
  text-align: right;
  font-size: 20px;
  font-weight: 600;
  color: #409EFF;
  padding: 15px;
  background: #ecf5ff;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.total-score--warning {
  color: #E6A23C;
  background: #fdf6ec;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

:deep(.el-table th) {
  background-color: #f8fafc !important;
  font-weight: 600;
  color: #2c3e50;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td) {
  background-color: #f8fafc;
}

/* 对话框样式优化 */
:deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  padding: 20px;
  margin: 0;
  background: #f8fafc;
  border-bottom: 1px solid #eef2f7;
}

:deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

:deep(.el-dialog__body) {
  padding: 30px;
}

:deep(.el-dialog__footer) {
  padding: 20px;
  border-top: 1px solid #eef2f7;
}

/* 步骤条样式优化 */
:deep(.el-steps) {
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

:deep(.el-step__title) {
  font-size: 16px;
  font-weight: 500;
}

:deep(.el-step__head.is-success) {
  color: #67C23A;
  border-color: #67C23A;
}

:deep(.el-step__title.is-success) {
  color: #67C23A;
}

/* 随机组题配置样式 */
.question-type-config {
  margin-bottom: 25px;
  padding: 20px;
  border: 1px solid #eef2f7;
  border-radius: 12px;
  background: #f8fafc;
}

.question-type-config h3 {
  margin: 0 0 15px 0;
  font-size: 18px;
  color: #2c3e50;
  font-weight: 600;
}

.difficulty-config {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.difficulty-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 10px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.difficulty-label {
  width: 70px;
  font-weight: 500;
  color: #2c3e50;
}

.question-count {
  color: #606266;
  margin: 0 15px;
  font-size: 14px;
}

.submit-button {
  margin-top: 30px;
  text-align: center;
}

.submit-button .el-button {
  padding: 12px 30px;
  font-size: 16px;
}

/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 4px;
}

::-webkit-scrollbar-track {
  background: #f5f7fa;
  border-radius: 4px;
}

/* 标签样式优化 */
:deep(.el-tag) {
  border-radius: 6px;
  padding: 6px 12px;
  font-weight: 500;
}

/* 选择器样式优化 */
:deep(.el-select) {
  width: 100%;
}

:deep(.el-select .el-input__wrapper) {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  border-radius: 8px;
}

/* 单选框组样式优化 */
:deep(.el-radio-group) {
  display: flex;
  gap: 20px;
}

:deep(.el-radio) {
  margin-right: 0;
}

/* 计算时间显示框样式 */
.calculated-time {
  padding: 10px 15px;
  color: #2c3e50;
  background-color: #f8fafc;
  border: 1px solid #eef2f7;
  border-radius: 8px;
  min-height: 40px;
  line-height: 20px;
  font-size: 14px;
}

/* 无数据提示样式 */
.no-data {
  text-align: center;
  color: #909399;
  padding: 40px;
  font-size: 16px;
  background: #f8fafc;
  border-radius: 12px;
  border: 1px dashed #e4e7ed;
}
</style>